// src/App.js
import React, { useState, useCallback, useEffect, useRef } from 'react';
import ReactFlow, {
  applyNodeChanges,
  applyEdgeChanges,
  addEdge,
  Background,
  useReactFlow,
  ReactFlowProvider
} from 'reactflow';
import 'reactflow/dist/style.css';
import InputNode, { validateInput } from './nodes/InputNode';
import OutputNode from './nodes/OutputNode';
import HttpNode from './nodes/HttpNode';
import ToolNode from './nodes/ToolNode';
import AgentNode from './nodes/AgentNode';


const nodeTypes = {
  inputNode: InputNode,
  outputNode: OutputNode,
  httpNode: HttpNode,
  toolNode: ToolNode,
  agentNode: AgentNode
};


function App() {
  const { screenToFlowPosition } = useReactFlow();
  const [nodes, setNodes] = useState([]);
  const [edges, setEdges] = useState([]);
  const [contextMenu, setContextMenu] = useState(null);

  // 用当前节点数量来作为节点的 ID
  const nodeIdCounter = useRef(0);

  // 双击节点处理
  const onNodeDoubleClick = useCallback((_, node) => {
   
  }, []);

  // 右键菜单
  const handlePaneContextMenu = (event) => {
    event.preventDefault();
    const position = screenToFlowPosition({
      x: event.clientX,
      y: event.clientY,
    });
    setContextMenu({
      flowPosition: position,
      screenPosition: { x: event.clientX, y: event.clientY }
    });
  };
  // 关闭菜单
  const closeContextMenu = useCallback(() => {
    setContextMenu(null);
  }, []);
  useEffect(() => {
    if (contextMenu) {
      document.addEventListener('click', closeContextMenu);
      return () => document.removeEventListener('click', closeContextMenu);
    }
  }, [contextMenu, closeContextMenu]);

  // 运行按钮
  const handleRun = async () => {
    
  };

  const onNodesChange = useCallback(
    (changes) => setNodes((nds) => applyNodeChanges(changes, nds)),
    []
  );

  const onEdgesChange = useCallback(
    (changes) => setEdges((eds) => applyEdgeChanges(changes, eds)),
    []
  );

  const onConnect = useCallback(
    (params) => setEdges((eds) => addEdge(
      { 
        ...params, 
        animated: true,
        style: { stroke: '#666' },
      }, 
      eds
    )),
    []
  );

  const createInputNode = useCallback(() => {
      const newNodeId = `input-${nodeIdCounter.current++}`;
      const newNode = {
        id: newNodeId,
        type: 'inputNode',
        position: contextMenu.flowPosition,
        data: {
          label: '输入节点',
          color: '#ffebe6',
          inputType: 'string',
          content: '',
          error: null,
          onChange: (value) => {
            setNodes(nds => nds.map(node => {
              if (node.id === newNodeId) {
                const error = validateInput(node.data.type, value);
                return {
                  ...node,
                  data: { ...node.data, content: value, error }
                };
              }
              return node;
            }));
          },
          onTypeChange: (newType) => {
            setNodes(nds => nds.map(node => {
              if (node.id === newNodeId) {
                let newContent = '';
                if (newType === 'boolean') newContent = 'true';
                if (newType === 'json') newContent = '{}';
                
                const error = validateInput(newType, newContent);
                return {
                  ...node,
                  data: { ...node.data, inputType: newType, content: newContent, error }
                };
              }
              return node;
            }));
          }
        }
      };
      
      setNodes(nds => nds.concat(newNode));
      closeContextMenu();
    }, [contextMenu, closeContextMenu]);

  const createOutputNode = useCallback(() => {
    const newNodeId = `output-${nodeIdCounter.current++}`;
    
    const newNode = {
      id: newNodeId,
      type: 'outputNode',
      position: contextMenu.flowPosition,
      data: {
        label: '输出节点',
        color: '#e6f3ff',
        content: '',
        selectedVariable: '',
        onVariableChange: (value) => {
          setNodes(nds => nds.map(node => 
            node.id === newNodeId 
              ? {...node, data: {...node.data, selectedVariable: value}} 
              : node
          ));
        }
      }
    };
    
    setNodes(nds => nds.concat(newNode));
    closeContextMenu();
  }, [contextMenu, closeContextMenu]);

  const createHttpNode = useCallback(() => {
    const newNodeId = `http-${nodeIdCounter.current++}`;
    
    const newNode = {
      id: newNodeId,
      type: 'httpNode',
      position: contextMenu.flowPosition,
      data: {
        label: 'HTTP 网络节点',
        url: 'https://api.example.com/data',
        method: 'GET',
        headers: [{ key: 'Content-Type', value: 'application/json' }],
        outputType: 'json',
        type: 'string',
        response: '',
        content: '',
        error: null,
        onAddHeader: () => {
          setNodes(nds => nds.map(node => 
            node.id === newNodeId ? {
              ...node,
              data: {
                ...node.data,
                headers: [...node.data.headers, { key: '', value: '' }]
              }
            } : node
          ));
        },
        onRemoveHeader: (index) => {
          setNodes(nds => nds.map(node => 
            node.id === newNodeId ? {
              ...node,
              data: {
                ...node.data,
                headers: node.data.headers.filter((_, i) => i !== index)
              }
            } : node
          ));
        },
        onHeaderChange: (index, field, value) => {
          setNodes(nds => nds.map(node => 
            node.id === newNodeId ? {
              ...node,
              data: {
                ...node.data,
                headers: node.data.headers.map((h, i) => 
                  i === index ? { ...h, [field]: value } : h
                )
              }
            } : node
          ));
        },
        onConfigChange: (key, value) => {
          setNodes(nds => nds.map(node => 
            node.id === newNodeId 
              ? {...node, data: {...node.data, [key]: value}} 
              : node
          ));
        }
      }
    };
    
    setNodes(nds => nds.concat(newNode));
    closeContextMenu();
  }, [contextMenu, closeContextMenu]);

  const createToolNode = useCallback(() => {
    const newNodeId = `tool-${nodeIdCounter.current++}`;
    const newNode = {
      id: newNodeId,
      type: 'toolNode',
      position: contextMenu.flowPosition,
      data: {
        label: '工具节点',
        desc: '执行 HTTP 请求 或 python 代码',
        toolName: 'HTTP API 接口工具',
        execType:'HTTP 请求', // HTTP 请求 或 python 代码
        params: [],
        codeContent: '',
        httpConfig: {url: '', method: 'GET', headers: [{key: 'Content-Type', value: 'application/json'}]},
        content: '',
        error: null,
        onConfigChange: (key, value) => {
          setNodes(nds => nds.map(node => 
            node.id === newNodeId 
              ? {...node, data: {...node.data, [key]: value}} 
              : node
          ));
        }
      }
    };
    setNodes(nds => nds.concat(newNode));
    closeContextMenu();
  }, [contextMenu, closeContextMenu]);

  const createAgentNode = useCallback(() => {
    const newNodeId = `agent-${nodeIdCounter.current++}`;
    
    const newNode = {
      id: newNodeId,
      type: 'agentNode',
      position: contextMenu.flowPosition,
      data: {
        label: '大模型智能体',
        desc: '你是一个有用的AI助手。',
        modelName: 'gpt-3.5-turbo',
        apiUrl: 'https://api.openai.com/v1/chat/completions',
        apiKey: 'xxx',
        maxPrompt: 2000,
        temperature: 0.7,
        content: '',
        error: null,
        onConfigChange: (key, value) => {
          setNodes(nds => nds.map(node => 
            node.id === newNodeId 
              ? {...node, data: {...node.data, [key]: value}} 
              : node
          ));
        }
      }
    };
    
    setNodes(nds => nds.concat(newNode));
    closeContextMenu();
  }, [contextMenu, closeContextMenu]);


  return (
    <div style={{ height: '100vh', position: 'relative' }}>
      <button
        onClick={handleRun}
        style={{
          position: 'absolute',
          top: 20,
          left: '50%',
          transform: 'translateX(-50%)',
          zIndex: 10,
          padding: '8px 20px',
          background: '#4CAF50',
          color: 'white',
          border: 'none',
          borderRadius: 20,
          cursor: 'pointer',
          boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
          fontSize: 14,
          fontWeight: 'bold',
        }}
      >
        ▶ 运行处理
      </button>

      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        onPaneContextMenu={handlePaneContextMenu}
        onNodeDoubleClick={onNodeDoubleClick}
        nodeTypes={nodeTypes}
        fitView
        connectionRadius={20}
        snapToGrid={true}
        snapGrid={[15, 15]}
        defaultEdgeOptions={{
          type: 'smoothstep',
          style: {
            strokeWidth: 2,
          },
        }}
      >
        <Background 
          color="#ddd"
          gap={25}
          style={{ backgroundColor: '#f8f9fa' }}
        />
      </ReactFlow>

      {contextMenu && (
        <div
          style={{
            position: 'fixed',
            top: contextMenu.screenPosition.y,
            left: contextMenu.screenPosition.x,
            background: 'white',
            boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
            borderRadius: 4,
            zIndex: 10,
          }}
          onClick={(e) => e.stopPropagation()}
        >
          <div
            style={{
              padding: '8px 16px',
              cursor: 'pointer',
              transition: 'background 0.2s',
              ':hover': {
                background: '#f5f5f5',
              },
            }}
            onClick={createInputNode}
          >
            添加输入节点
          </div>

          <div
            style={{
              padding: '8px 16px',
              cursor: 'pointer',
              transition: 'background 0.2s',
              ':hover': {
                background: '#f5f5f5',
              },
            }}
            onClick={createOutputNode}
          >
            添加输出节点
          </div>
          <div
            style={{ padding: '8px 16px', cursor: 'pointer' }}
            onClick={createHttpNode}
          >
            添加HTTP网络节点
          </div>
          <div
            style={{ padding: '8px 16px', cursor: 'pointer' }}
            onClick={createToolNode}
          >
            添工具节点
          </div>
          <div
            style={{ padding: '8px 16px', cursor: 'pointer' }}
            onClick={createAgentNode}
          >
            添加对话节点
          </div>
          
        </div>
      )}

    </div>
  );
}

export default function FlowWrapper() {
  return (
    <ReactFlowProvider>
      <App />
    </ReactFlowProvider>
  );
}
